<?php
/*
 * 2017-03-22 
 * 栏目分类操作类 
 * */
class category{
	public $G;
	public function __construct(&$G){
		$this->G = $G;
	}

	public function _init(){
		$this->dbpdo=$this->G->loadclass('dbpdo');
		$this->pages=$this->G->loadclass('pages');
		$this->routes=$this->G->loadclass('routes');
		$this->webconfig=$this->G->loadclass('webconfig');
	}

	//获取所有分类
	public function getAll($condition=array(),$orderby='inrow'){
		return $this->dbpdo->query("category",'*',$condition,"",$orderby,"","","","id");
	}

	public function getList($Spage,$Snumber=PAGED,$condition=array(),$orderby='inrow',$UrlStyle=""){
		$rs=array();
		//下句有报错 开始页码为1时（记录为0开始）只能转为字符，否则显示全部内容
		$rs['data']=$this->dbpdo->query("category",'*',$condition,"",$orderby,"",strval(intval($Spage-1)*$Snumber),$Snumber);
		$t=$this->dbpdo->getOne("category",'count(*) AS total',$condition);
		$Intpages = $this->pages->set_page_info($t['total'],$Snumber,$UrlStyle);
		if($rs){
			$rs['pages']=$Intpages;
			$rs['total'] = $t['total'];
		}
		return $rs;
	}

	//根据条件获取所有分类id
	public function getCids($condition=array()){	 
		$cats=$this->dbpdo->query("category",'*',$condition,"","","","","","id");
		$ids='';
		if($cats){
			foreach($cats as $v){
				if($ids==''){
					$ids=$v['id'];
				}else{
					$ids=$ids.','.$v['id'];
				}		
			}
			return $ids;
		}else{
			return false;
		}	
	}

    //根据条件获取所有子类
	public function getSunCat($condition=array(),$orderby='inrow'){
		$CatList=$this->dbpdo->query("category",'*',$condition,"",$orderby);
		if($CatList){
			return $CatList;
		}else{
			return false;
		}
	}
    
	//根据分类ID获取所有分类
	public function getSunByCid($IntCid=0,$orderby='inrow desc'){
		$CatList=$this->dbpdo->query("category",'*',array('parent_id'=>$IntCid,'isview'=>1),"",$orderby);
		if($CatList){
			return $CatList;
		}else{
			return false;
		}
	}

	//根据分类ID获取所有分类
	public function getParentByCid($IntCid){
		return $this->dbpdo->getOne("category",'*',array('parent_id'=>$IntCid));
	}

	//根据分类目录名获取一条记录
	public function getOne($condition=array()){
		if(empty($condition)||is_array($condition)){
			return $this->dbpdo->getOne("category",'*',$condition);
		}else{
			return false;
		}
		
	}

	//根据分类ID获取一条记录
	public function getOneByID($IntID){
		return $this->dbpdo->getOne("category",'*',array('id'=>$IntID));
	}

	//根据分类目录名获取一条记录
	public function getOneByCatalog($catalog_name){
		return $this->dbpdo->getOne("category",'*',array('catalog_name'=>$catalog_name));
	}

	//新增分类保存
	public function save($dsw){
		$IntRank=1;
		if($dsw['parent_id']>0){
			$s=$this->dbpdo->getOne("category",'*',array('id'=>$dsw['parent_id']));
			$IntRank=$s['rank']+1;
		}
		$dsw['rank']=$IntRank;
		$this->dbpdo->insert_data("category",$dsw);
		return $this->dbpdo->getInsertId();
	}

	//新增分类保存
	public function update($dsw=array(),$condition=array()){
		return $this->dbpdo->update_data("category",$dsw,$condition);
	}

	//分类删除
	public function del($IntID){
		return $this->dbpdo->remove("category",array("id"=>$IntID));
	}

	//是否显示
	public function isview($IntID){
		$Strok="";
		$list=$this->dbpdo->getOne("category","*",array('id' => $IntID));
		if($list['isview']==0){
			$row=array(
				'isview'=>1
			);
			$Strok='<span class="glyphicon glyphicon-eye-open"></span>';
		}else{
			$row=array(
				'isview'=>0
			);
			$Strok='<span class="glyphicon glyphicon-eye-close"></span>';
		}
		$this->dbpdo->update_data('category',$row,array('id' => $IntID));
		return $Strok;
	}

	//是否在菜单显示
	public function ismenu($IntID){
		$Strok="";
		$list=$this->dbpdo->getOne("category","*",array('id' => $IntID));
		if($list['ismenu']==0){
			$row=array(
				'ismenu'=>1
			);
			$Strok='<span class="glyphicon glyphicon-eye-open"></span>';
		}else{
			$row=array(
				'ismenu'=>0
			);
			$Strok='<span class="glyphicon glyphicon-eye-close"></span>';
		}
		$this->dbpdo->update_data('category',$row,array('id' => $IntID));
		return $Strok;
	}

	//是否在首页显示
	public function isindex($IntID){
		$Strok="";
		$list=$this->dbpdo->getOne("category","*",array('id' => $IntID));
		if($list['isindex']==0){
			$row=array(
				'isindex'=>1
			);
			$Strok='<span class="glyphicon glyphicon-eye-open"></span>';
		}else{
			$row=array(
				'isindex'=>0
			);
			$Strok='<span class="glyphicon glyphicon-eye-close"></span>';
		}
		$this->dbpdo->update_data('category',$row,array('id' => $IntID));
		return $Strok;
	}

	//检查目录名称是否存在
	public function getCheckInput($SInput){
		$Strok="";
		$list=$this->dbpdo->getOne("category","*",array('catalog_name' => $SInput));
		if($list['catalog_name']){
			$Strok='<span class="btn-danger btn">目录名已经存在，请重新输入</span>';
		}else{
			$Strok='<span class="btn-success btn">恭喜您，可以创建</span>';
		}
		return $Strok;
	}

	/**
	 * [getArrTree 获取树状数组分类 非递归]
	 * @param  [type] $cats [分类数组数据]
	 */
	public function getArrTree($cats){  
		$tree = array();  
		//第一步，将分类id作为数组key,并创建children单元  
		foreach($cats as $category){  
		    $tree[$category['id']] = $category;  
		    $tree[$category['id']]['children'] = array();  
		}  
		//第二步，利用引用，将每个分类添加到父类children数组中，这样一次遍历即可形成树形结构。  
		foreach($tree as $key=>$item){  
		    if($item['parent_id'] != 0){  
		        $tree[$item['parent_id']]['children'][] = &$tree[$key];//注意：此处必须传引用传递，循环后面的数组的改变，同样会影响此时的数组  
		        if($tree[$key]['children'] == null){  
		            unset($tree[$key]['children']); //如果children为空，则删除该children元素（可选）  
		        }  
		    }  
		}  
		////第三步，删除无用的非根节点数据  
		foreach($tree as $key=>$category){  
		    if($category['parent_id'] != 0){  
		        unset($tree[$key]);  
		    }  
		}
		return $tree; 
	}
	
	/**
	 * [getTree 获取树状分类]
	 * 时间:20181026
	 * @param  [array] $condition  [条件]
	 * @param  integer $pid   [父ID]
	 * @param  integer $level [级别节点]
	 * @return [array]        [返回分类数组数据,分类名称带--]
	 * 
	 * 举例
	 * $ListCats=$this->category->getAll();//先根据条件获取分类
	 * $array = $this->category->getTreeByData($ListCats);//根据获取到的分类再转为树形结构分类
	 * foreach($array as $value){
	       echo $value['cat_name'].'<br />';
	    }
	 */
	public function getTreeByData($data='', $pid =0, $level = 0){
		if(empty($data)){
			return false;
		}
		//声明静态数组,避免递归调用时,多次声明导致数组覆盖 
		static $list = [];
		foreach ($data as $key => $value){
			//第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点 
			if ($value['parent_id'] == $pid){
				//父节点为根节点的节点,级别为0，也就是第一级 
				$value['level'] = $level;
				//把数组放到list中
				$value['cat_name']=str_repeat('--',$value['level']).$value['cat_name'];
				$list[] = $value;
				//把这个节点从数组中移除,减少后续递归消耗 
				unset($data[$key]);
				//开始递归,查找父ID为该节点ID的节点,级别则为原级别+1 
				$this->getTree($data, $value['id'], $level+1);
			}
		}
		return $list;
	}

	/**
	 * 根据条件获取树形结构分类
	 */
	public function getTree($condition='', $pid =0, $level = 0){
		$data=$this->getAll($condition);
		//声明静态数组,避免递归调用时,多次声明导致数组覆盖
		if(!empty($data)){
			static $list = [];
			foreach ($data as $key => $value){
				//第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点 
				if ($value['parent_id'] == $pid){
					//父节点为根节点的节点,级别为0，也就是第一级 
					$value['level'] = $level;
					//把数组放到list中
					$value['cat_name']=str_repeat('--',$value['level']).$value['cat_name'];
					$list[] = $value;
					//把这个节点从数组中移除,减少后续递归消耗 
					unset($data[$key]);
					//开始递归,查找父ID为该节点ID的节点,级别则为原级别+1 
					$this->getTree($condition='', $value['id'], $level+1);
				}
			}
			return $list;
		}
	}

	public function getSunByRank($rank=1){
		return $this->dbpdo->query("category","*",array('rank'=>$rank));
	}

	/*
	 * 获取面包屑导航
	 * 1、将当前ID记录查询，根据rank做循环
	 * 2、每次将上级记录保持到数组pid中
	 * 3、反序列出上级记录
	*/
	public function getNavCrumbByCid($IntCid){
		$CurCat=$this->getOneByID($IntCid);
		$IntPid=$CurCat['parent_id'];
		$ForCount=0;
		if($CurCat&&$IntPid<>0){
			while($IntPid<>0){
				$Pid[$ForCount]=$this->getOneByID($IntPid);
				$IntPid=$Pid[$ForCount]['parent_id'];
				$ForCount++;
			}
			$NewPid=array_reverse($Pid);//数组反序
			foreach($NewPid as $key=>$value){
				$NavPath='<a href="/'.$value['catalog_name'].'/">'.$value['cat_name'].'</a> > ';
				if($SResult==""){
					$SResult=$NavPath;
				}else{
					$SResult=$SResult.$NavPath;
				}	
			}
		}
		$WebSite=$this->webconfig->getWebConfig();
		//$SResult='<a href="'.$WebSite['website']['web_dir'].$WebSite['website']['web_index'].'">'.$WebSite['website']['web_name'].'</a> > '.$SResult;
		$SResult='<a href="'.SITE_WEB.'/">'.$WebSite['website']['home_title'].'</a> > '.$SResult;
		$SResult='当前位置：'.$SResult.'<a class="active" href="'.SITE_WEB.'/'.$CurCat['catalog_name'].'/">'.$CurCat['cat_name'].'</a> > ';
		return $SResult;
	}

	//增加浏览次数
	public function updateView($catalog_name){
		$intview=$this->dbpdo->getOne("category",'*',array('catalog_name'=>$catalog_name));
		$dsw=array(
			"cat_view"=>$intview['cat_view']+1
		);
		return $this->dbpdo->update_data("category",$dsw,array('catalog_name'=>$catalog_name));
	}
}
?>
